package com.maodou.android.ui.page

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.maodou.core.datastore.DataStore
import com.maodou.android.data.model.User
import com.maodou.core.model.UserInfo
import kotlinx.coroutines.launch

/**
 * 演示页面
 */
@Composable
fun DataStoreDemoScreen(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // 使用 core 封装的 DataStore：聚合了 MMKV（KeyValue）与 Room 缓存（Object/List）
    val ds = remember { DataStore.create(context) }

    var loginStatus by remember { mutableStateOf("-") }
    var loginInfoText by remember { mutableStateOf("-") }
    var objectCacheText by remember { mutableStateOf("-") }
    var listCacheText by remember { mutableStateOf("-") }

    LaunchedEffect(Unit) {
        loginStatus = "isLoggedIn = ${ds.keyValue.isLoggedIn()}"
        loginInfoText = ds.keyValue.getObject("USER_INFO", UserInfo::class.java)?.let { "${it.id}/${it.role ?: "-"}" } ?: "<null>"
    }

    Column(modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Text("DataStore Demo (MMKV + Room)", style = MaterialTheme.typography.titleLarge)

        // MMKV：登录状态与登录信息
        Text("— MMKV（KeyValueStorage） —", style = MaterialTheme.typography.titleMedium)
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = {
                val newVal = !(ds.keyValue.isLoggedIn())
                ds.keyValue.setLoggedIn(newVal)
                loginStatus = "isLoggedIn = ${newVal}"
            }) { Text("切换登录状态") }

            Button(onClick = {
                val info = UserInfo(id = "u-${System.currentTimeMillis() % 10000}", token = "t-${System.nanoTime()}", nickName = "MaoDou")
                ds.keyValue.putObject("USER_INFO",info,UserInfo::class.java)
                loginInfoText = "${info.id}/${info.nickName}"
            }) { Text("保存登录信息") }

            Button(onClick = {
                val info = ds.keyValue.getObject("USER_INFO", UserInfo::class.java)
                loginInfoText = info?.let { "${it.id}/${it.nickName ?: "-"}" } ?: "<null>"
            }) { Text("读取登录信息") }

            Button(onClick = {
                ds.keyValue.clearAll()
                loginStatus = "isLoggedIn = ${ds.keyValue.isLoggedIn()}"
                loginInfoText = ds.keyValue.getObject("USER_INFO", UserInfo::class.java)?.toString() ?: "<null>"
            }) { Text("清空 KV") }
        }
        Text(loginStatus)
        Text("loginInfo = ${loginInfoText}")

        // Room：对象缓存（带 TTL）
        Text("— Room（ObjectCacheStore） —", style = MaterialTheme.typography.titleMedium)
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = {
                scope.launch {
                    val user = User(id = 1, name = "Alice", email = "alice@example.com", username = "alice")
                    ds.objectCache.put("demo_user", user, ttlSeconds = 5)
                    objectCacheText = "写入对象缓存：${user.name} (ttl=5s)"
                }
            }) { Text("写入对象缓存") }

            Button(onClick = {
                scope.launch {
                    val u = ds.objectCache.get<User>("demo_user", acceptExpired = false)
                    objectCacheText = u?.let { "读取对象缓存：${it.name}" } ?: "对象缓存为空或已过期"
                }
            }) { Text("读取(不过期)") }

            Button(onClick = {
                scope.launch {
                    val u = ds.objectCache.get<User>("demo_user", acceptExpired = true)
                    objectCacheText = u?.let { "读取对象缓存（允许过期）：${it.name}" } ?: "对象缓存为空"
                }
            }) { Text("读取(可过期)") }
        }
        Text(objectCacheText)

        // Room：列表缓存
        Text("— Room（ListCacheStore） —", style = MaterialTheme.typography.titleMedium)
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = {
                scope.launch {
                    val list = listOf(
                        User(1, "Alice", "alice@example.com", "alice"),
                        User(2, "Bob", "bob@example.com", "bob"),
                        User(3, "Carol", "carol@example.com", "carol")
                    )
                    ds.listCache.putList("demo_users", list)
                    listCacheText = "写入列表缓存：size=${list.size}"
                }
            }) { Text("写入列表缓存") }

            Button(onClick = {
                scope.launch {
                    val list = ds.listCache.getList<User>("demo_users")
                    listCacheText = list?.let { "读取列表缓存：size=${it.size}" } ?: "列表缓存为空"
                }
            }) { Text("读取列表缓存") }
        }
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Button(onClick = {
                scope.launch {
                    val n = ds.objectCache.clearExpired()
                    listCacheText = "清理过期：受影响行=${n}"
                }
            }) { Text("清理过期") }

            Button(onClick = {
                scope.launch {
                    ds.objectCache.clearAll()
                    objectCacheText = "对象缓存已清空"
                    ds.listCache.clearAll()
                    listCacheText = "列表缓存已清空"
                }
            }) { Text("清空全部缓存") }
        }
        Text(listCacheText)
    }
}